<?php

/**
 * ScheduleHandler takes care of downloading and parsing the schedule.
 *
 * @author Markus Deutsch <Markus.Deutsch.ITM09@fh-joanneum.at>
 */
class ScheduleHandler {
    private $course;
    private $year;
    private $key;
    public $ics;
    private $url;
    public $status;
    
    private $events;
    private $raw_events;
    
    /**
     * The constructor expects all data necessary to download schedule.
     * 
     * @param String $course The three-letter-representation of the course
     * @param int $year The four-digit year of the class
     * @param String $key A valid FHPI key
     */
    function __construct($course, $year, $key){
        $this->course = $course;
        $this->year = $year;
        $this->key = $key;
        
        $this->events = array();
        $this->raw_events = array();
        
        if(!isValidApp($key)){
            $this->status = "INVALID_KEY";
        } else if ($course == null || $year == null){
            $this->status = "INCOMPLETE_DATA";
        } else if (strlen($course) != 3 || !is_numeric($year) || $year < 2000 || $year > date("Y")){
            $this->status = "INVALID_DATA";
        } else {
            $this->status = "OK";
        }
        
        // Log this visit
        logger("Schedule", $this->status, $key);
        
        // Set the URL
        $this->url = 'http://almaty.fh-joanneum.at/stundenplan/search.php?q="'.$this->course.'+'.$this->year.'"';
    }
    
    /**
     * Retrieves data from the server.
     * 
     * @return boolean False only if specified data was invalid.
     */
    function retrieve(){
        if($this->status == "OK"){
            $c = curl_init($this->url);
            curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
            $this->ics = curl_exec($c);
            curl_close($c);
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * Parses previously retrieved data.
     * 
     * @return boolean False if specified data was incorrect or the retrieved string is empty.
     */
    function parse(){
        if($this->status == "OK" && strlen($this->ics) > 0){
            // Load every line of ICS file into array
            $schedule = explode("\n", $this->ics);
            // Iterate over every line.
            foreach($schedule as $s){
                if($s == "BEGIN:VEVENT" && isset($a)){
                    if(count($a) > 2){
                        $this->raw_events[] = $a;
                    }
                    unset($a);
                } else if ($s != "END:VEVENT"){
                    $a[] = $s;
                } else {
                    //$a = array();
                }
            }
            
            // Last event must not be ignored - add it now.
            $this->raw_events[] = $a;
            
            /*
             * Now, every event-block is saved seperately 
             * in the $raw_events array.
             */
            
            /*
             * Take every block, iterate over the lines, and save the information we want.
             */
            foreach($this->raw_events as $raw_event){
                $e = new Event($this->course, $this->year);
                
                foreach($raw_event as $line){
                    // Handle start time
                    if(stristr($line, "DTSTART")){
                        /*
                         * The line is ripped in two and the last part which represents the date
                         * is converted to an UNIX timestamp and saved to the event.
                         */
                        $helper = explode(":", $line);
                        $e->setStart(strtotime(trim($helper[1])));
                    }
                    // Handle end time
                    if(stristr($line, "DTEND")){
                        $helper = explode(":", $line);
                        $e->setEnd(strtotime(trim($helper[1])));
                    }
                    // Handle summary
                    if(stristr($line, "SUMMARY:")){
                        $helper = explode(":", $line);
                        $items = explode("\,", $helper[1]);
                        
                        // Handle title
                        $e->setTitle(trim($items[0]));
                        
                        // Handle location
                        $e->setLocation(trim(substr($items[count($items) - 1], 0, -10)));
                        
                        // Handle type
                        $e->setType(strtoupper(trim($items[count($items) - 2])));
                        
                        // Handle lecturer
                        $e->setLecturer(trim($items[count($items) - 3]));
                    }
                }
                
                $this->events[] = $e;
                unset($e);
            }
            
            
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * Get all Events found by the parser.
     * 
     * @return Array Array of Events found by parser. 
     */
    function getResults(){
        return $this->events;
    }
}

?>